package com.example.springboot.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;

import cn.hutool.core.io.FileUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;






@RestController
@RequestMapping("/file")
public class FileController {
    
    @Value("${ip}")
    String ip;
    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH = System.getProperty("user.dir")+File.separator+"files";//D:\Desktop\web应用开发\bookstore\springboot\files


    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        String originalFileName=file.getOriginalFilename();//原始文件名称
        //aa.png
        String mainName=FileUtil.mainName(originalFileName);//aa
        String extName=FileUtil.extName(originalFileName);//png
        if(!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);//如果当前文件的父级目录不存在，就创建
        }
        if(FileUtil.exist(ROOT_PATH+File.separator+originalFileName)){
            originalFileName=System.currentTimeMillis()+"_"+mainName+"."+extName;
        }
        File saveFile=new File(ROOT_PATH+File.separator+originalFileName);//文件存储的目录 D:\Desktop\web应用开发\bookstore\files\aaa.png
        file.transferTo(saveFile);
        String url = "http://"+ip+":"+port+"/file/download/"+originalFileName;
        return Result.success(url);//返回文件的链接，这个文件是文件的下载地址，这个下载地址就是我的后台提供出来的
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName,HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH+File.separator+fileName;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes=FileUtil.readBytes(filePath);
        ServletOutputStream outputStream=response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
    
}
